#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (C) 2006-2007 Ville Leskinen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

import sys
import igCreator

from optparse import OptionParser
from igCreator.config import *
from igCreator.gallery import Gallery, ListenableGallery
from igCreator.imagelist import ImageList, ListenableImageList, ImageBox, ImageListOptions
from igCreator.errors import *
from igCreator.listener import *

class ProgressBarListener(Listener):
	def __init__(self):
		Listener.__init__(self)
		self.message = None
		self.progressBar = self._repeatChar(' ', 20)
		self.printString = ""

		self._bar = self._repeatChar('=', 19) + '>'
	
	def _repeatChar(self, char, times):
		returnString = ""
		for i in range(times):
			returnString += char

		return returnString

	def _printProgress(self, percentDone, message):

		sys.stdout.flush()
		# lets clean the terminal
		sys.stdout.write(self._repeatChar('\b',len(self.printString)))
		sys.stdout.write(self._repeatChar(' ',len(self.printString)))
		sys.stdout.write(self._repeatChar('\b',len(self.printString)))

		progress = 20.0 * (float(percentDone)/ 100.0)
		progress = int(progress)

		self.progressBar = self._bar[20-progress:] + self._repeatChar(' ', 20 - progress)
#		self.progressBar = self._repeatChar('=', progress - 1) + '>' + self._repeatChar(' ', 20 - progress)

		self.printString = "Progress: [%s] %i%% %s" % (self.progressBar, percentDone, message)
		sys.stdout.write(self.printString)


		
	def eventHappening(self, event):
		nowDone = self.done
		Listener.eventHappening(self, event)

		percentDone = int(float(nowDone)/float(self.totalLength) * 100)

		self._printProgress(percentDone, event.message)
	


	def finished(self):
		self._printProgress(100, "Done!")
		print ""
		self.progressLog.close()

def ParseSizeOpts(picOpt, thumbOpt):

	if picOpt == 'help' or thumbOpt == 'help':
		print "Possible values for sizes are (use only one) \
			\n\t<pixels>x<pixels>\t box where the picture is fitted \
			\n\twidth=<pixels>\t\t max width \
			\n\theight=<pixels>\t\t max height \
			\n\tlong=<pixels>\t\t max length for longer side \
			\n\tshort=<pixels>\t\t max length for shorter side \
			\n\nAll of these options keep the picture's aspect ratio."

		sys.exit(0)

	picBox = None
	thumbBox = None

	if picOpt:
		picBox = ImageBox()
		picBox.parseString(picOpt)
	if thumbOpt:
		thumbBox = ImageBox()
		thumbBox.parseString(thumbOpt)

	return (picBox, thumbBox)

def PrintFilterHelp():
	print "Possible values for the filter are \
		\n\tnearest\t\t fastest but poor quality \
		\n\tbilinear\t fast and ok quality \
		\n\tbicubic\t\t slightly better than bilinear but also slower \
		\n\tantialias\t best quality but also the slowest (default)"
	sys.exit(0)

def main(argv):

	configfiles = [ ".igcreator", "/etc/igcreator"]
	cmdLineOpts = CmdLineConfig(argv)

	if cmdLineOpts.configfile:
		configfiles.insert(0, cmdLineOpts.configfile)

	cfgFileOpts = CfgFileConfig(configfiles)

	cfg = GenerateConfig([cmdLineOpts, cfgFileOpts])

	if cfg.config['filter'] == 'help':
		PrintFilterHelp()

	ilOpts = ImageListOptions()

	(picBox, thumbBox) = ParseSizeOpts(cfg.config['size'], cfg.config['thumbsize'])
	if picBox != None:
		ilOpts.setPicBox(picBox)
	
	if thumbBox != None:
		ilOpts.setThumbBox(thumbBox)
	else:
		print "No thumbnail size give. Using width=150"
		ilOpts.setThumbBox(ImageBox(width=150))

	if cfg.config['filter']:
		ilOpts.setResizeFilter(cfg.config['filter'])
		print "Using filter: %s" % (cfg.config['filter'])

	il = None

	if cfg.config['imagedir']:
		if cfg.config['verbose']:
			il = ImageList()
		else:
			il = ListenableImageList()
		il.readListFromPath(cfg.config['imagedir'])
	else:
		if not cfg.config['images']:
			sys.stderr.write("Error: No images specified\n")
			sys.exit(-1)
		if cfg.config['verbose']:
			il = ImageList(cfg.config['images'])
		else:
			il = ListenableImageList(cfg.config['images'])
	

	il.setOptions(ilOpts)

	if cfg.config['verbose']:
		g = Gallery(il)
	else:
		g = ListenableGallery(il)
		
	if cfg.config['outputdir']:
		g.setPath(cfg.config['outputdir'])

	if cfg.config['pictemplate']:
		g.readPicTemplate(cfg.config['pictemplate'])

	if cfg.config['thumbtemplate']:
		g.readThumbTemplate(cfg.config['thumbtemplate'])

	if cfg.config['heading']:
		g.setHeading(cfg.config['heading'])


	pbListener = None

	if not cfg.config['verbose']:
		pbListener = ProgressBarListener()
	
		il.addListener(pbListener)
		g.addListener(pbListener)

	g.setCSSFile(cfg.config['custom-css'])
	
	g.create()

	if pbListener:
		pbListener.finished()
	
	
if __name__ == '__main__':
	try:
		main(sys.argv)
	except igCreatorError, se:
		sys.stderr.write("Program error: %s\n" % (se))
		sys.exit(se.errorCode)

	except SystemExit:
		pass
	except KeyboardInterrupt:
		print "Caught KeyboardInterrupt"
	
#	except Exception, e:
#		sys.stderr.write("Error: %s\n" % (e))
#		sys.exit(-1)
